package lab3p2;

/**
 * <p>Title: MyListModel for Lab #3 Part 2</p>
 * <p>Description: CSIS 343 Lab on Model-View-Controller</p>
 * 
 * @author tony
 * @date  08.04.2013
 * @email anthony.varghese@uwrf.edu
 * @version 2
 *
 */


import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Collections;
import java.util.LinkedList;
import java.util.Scanner;

import javax.swing.AbstractListModel;


public class MyListModel extends AbstractListModel<Star> {

	/**
	 * Data members
	 */
	private static final long serialVersionUID = 1L;
	/*
	 * The actual implementation uses a linked list data structure.
	 */
	private LinkedList<Star> data;
	
	
	/**
	 * Default constructor creates an empty list
	 */
	public MyListModel() {
		data = new LinkedList<Star>();
	}

	/**
	 * Read star data from a file.
	 * @param filename
	 */
	public MyListModel(final String INPUT_FILE ) {
		data = new LinkedList<Star>();
		try {
			Scanner in = new Scanner( new FileReader( INPUT_FILE ) );
			// read in and ignore the first line of the file
			in.nextLine();
			while (in.hasNext()){
				String name = in.next();
				double sunM = in.nextDouble();
				int    jupM = in.nextInt();
				data.add( new Star( name, jupM, sunM) );
			}
			in.close();
			
		} catch (FileNotFoundException e) {
			System.err.println("Not able to open file: " + INPUT_FILE );
			System.exit( -1 );
		}
	}

	public Star getElementAt(int index) {
		return data.get( index );
	}

	public int getSize() {
		return data.size();
	}

	/**
	 * These are triggered by the controller
	 */
	public void sort(){
		Collections.sort( data );
		System.out.println("Sorting ... ");
	}
	
	public void unsort(){
		System.out.println("Shuffling ... ");
		LinkedList<Star> newdata = new LinkedList<Star>();
		while (data.size()>0)
			newdata.add( data.remove( (int) ( Math.random() * data.size() ) ) );

		data = newdata;
	}

}
